package org.summerframework.component.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.summerframework.component.security.LoginData;
import org.summerframework.component.security.context.RequestContextFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author 石超
 */
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("start insert fill ....");
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        LoginData loginData = RequestContextFactory.getLoginData();

        if (loginData != null && loginData.isLogin()) {
            this.strictInsertFill(metaObject, "createBy", Long.class, loginData.getUserId());
            this.strictInsertFill(metaObject, "updateBy", Long.class, loginData.getUserId());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("start update fill ....");
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        LoginData loginData = RequestContextFactory.getLoginData();

        if (loginData != null && loginData.isLogin()) {
            this.strictUpdateFill(metaObject, "updateBy", Long.class, loginData.getUserId());
        }
    }
}
